package com.stark.lab.covid19statistics.util;

import com.stark.lab.covid19statistics.dto.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Component
public class DataUtil {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    List<RegionStats> regionStatsList = new ArrayList<>();

    public InputStream pullData2inputStream() throws IOException {
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create("https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"))
                .headers(httpHeaders -> {httpHeaders.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36");})
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();
        return body.getInputStream();
     }

     public void refreshData() {
         CSVParser csvParser = null;
         try {
             csvParser = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(new InputStreamReader(pullData2inputStream()));
         } catch (IOException e) {
             e.printStackTrace();
             return;
         }
         Iterable<CSVRecord> records = null;
         try {
             records = csvParser.getRecords();
         } catch (IOException e) {
             logger.error("getRecords exception");
             e.printStackTrace();
         }
         if(records==null)
             return;
         regionStatsList = new ArrayList<>();
         List<String> headers = csvParser.getHeaderNames();
         for (CSVRecord record : records) {
             RegionStats regionStats = new RegionStats();
             regionStats.setCountry(record.get("Country/Region"));
             regionStats.setProvince(record.get("Province/State"));
             try{
                 regionStats.setLatitude(Double.parseDouble(record.get("Lat")));
                 regionStats.setLongitude(Double.parseDouble(record.get("Long")));
             }catch (Exception e){ }
             List<RegionStats.DateStats> dateStatsList =new ArrayList<>();
             for(int i=4;i<headers.size();i++){
                 RegionStats.DateStats dateStats = new RegionStats.DateStats();
                 dateStats.setDate(headers.get(i));
                 dateStats.setCount(Integer.parseInt(record.get(i)));
                 dateStatsList.add(dateStats);
             }
             regionStats.setDateStatsList(dateStatsList);
             regionStats.setLatestTotalCases(dateStatsList.get(dateStatsList.size()-1).getCount());
             regionStatsList.add(regionStats);
         }
         logger.info("Refresh done.Result:{}",regionStatsList.size());
     }

     public List<RegionStats> getRegionStatsList(){
        if(regionStatsList.isEmpty())
            refreshData();
        return regionStatsList;
     }


}
